<template>
    <view class="container">
        <!-- 头部信息 -->
        <view class="header-info">
            <view class="balance-info">
                <text class="balance-label">可提现金额</text>
                <text class="balance-amount">¥{{ availableAmount }}</text>
            </view>
            <view class="apply-btn" @click="showApplyModal">
                <text class="apply-text">申请提现</text>
            </view>
        </view>

        <!-- 提现记录列表 -->
        <view class="record-list">
            <view class="list-header">
                <text class="list-title">提现记录</text>
            </view>
            
            <view v-if="withdrawList.length === 0" class="empty-state">
                <text class="empty-text">暂无提现记录</text>
            </view>
            
            <view v-else>
                <view class="record-item" v-for="(item, index) in withdrawList" :key="index">
                    <view class="record-header">
                        <text class="record-num">{{ item.withdrawNum }}</text>
                        <text class="record-status" :class="'status-' + item.withdrawStatus.toLowerCase()">
                            {{ getStatusText(item.withdrawStatus) }}
                        </text>
                    </view>
                    
                    <view class="record-content">
                        <view class="amount-info">
                            <text class="amount-label">提现金额：</text>
                            <text class="amount-value">¥{{ item.totalAmount }}</text>
                        </view>
                        <view class="amount-info">
                            <text class="amount-label">手续费：</text>
                            <text class="amount-value">¥{{ item.feeAmount }}</text>
                        </view>
                        <view class="amount-info">
                            <text class="amount-label">实际到账：</text>
                            <text class="amount-value highlight">¥{{ item.realAmount }}</text>
                        </view>
                    </view>
                    
                    <view class="record-footer">
                        <text class="time-text">申请时间：{{ item.withdrawTime }}</text>
                        <text v-if="item.handleTime" class="time-text">处理时间：{{ item.handleTime }}</text>
                    </view>
                    
                    <!-- 审批通过显示收款按钮 -->
                    <view v-if="item.withdrawStatus === '2'" class="action-btn">
                        <button class="receive-btn" @click="confirmReceive(item)">去收款</button>
                    </view>
                    <!-- 已收款状态显示 -->
                    <view v-if="item.withdrawStatus === '100'" class="action-btn">
                        <text class="received-text">已收款</text>
                    </view>
                </view>
            </view>
        </view>

        <!-- 申请提现弹窗 -->
        <view v-if="showModal" class="modal-overlay" @click="hideApplyModal">
            <view class="modal-content" @click.stop>
                <view class="modal-header">
                    <text class="modal-title">申请提现</text>
                    <text class="modal-close" @click="hideApplyModal">×</text>
                </view>
                
                <view class="modal-body">
                    <view class="form-item">
                        <text class="form-label">可提现金额</text>
                        <text class="form-value">¥{{ availableAmount }}</text>
                    </view>
                    
                    <view class="form-item">
                        <text class="form-label">实名姓名</text>
                        <input 
                            class="form-input" 
                            type="text" 
                            placeholder="请输入实名姓名"
                            v-model="username"
                        />
                    </view>
                    
                    <view class="form-item">
                        <text class="form-label">提现金额</text>
                        <input 
                            class="form-input" 
                            type="digit" 
                            placeholder="请输入提现金额"
                            v-model="applyAmount"
                            @input="validateAmount"
                        />
                    </view>
                    
                    <view class="tips">
                        <text class="tips-text">• 请填写真实姓名，用于提现转账</text>
                        <text class="tips-text">• 最低提现金额：¥1，最高¥200</text>
                        <text class="tips-text">• 提现将收取一定手续费</text>
                        <text class="tips-text">• 审批通过后需要您确认收款</text>
                    </view>
                </view>
                
                <view class="modal-footer">
                    <button class="cancel-btn" @click="hideApplyModal">取消</button>
                    <button class="confirm-btn" @click="submitApply" :disabled="!canSubmit">确认申请</button>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            availableAmount: 0, // 可提现金额
            withdrawList: [], // 提现记录列表
            showModal: false, // 是否显示申请弹窗
            applyAmount: '', // 申请提现金额
            username: '', // 实名姓名
            pageNum: 1,
            pageSize: 10,
            loading: false
        }
    },
    computed: {
        canSubmit() {
            const amount = parseFloat(this.applyAmount);
            return this.username.trim() !== '' && amount < 200 && amount >= 1 && amount <= this.availableAmount;
        }
    },
    onLoad() {
        this.loadUserInfo();
        this.loadWithdrawList();
    },
    onPullDownRefresh() {
        this.pageNum = 1;
        this.loadWithdrawList();
    },
    onReachBottom() {
        this.loadMore();
    },
    methods: {
        // 加载用户信息
        loadUserInfo() {
            this.$api.req('/station/member/get', {}, 'get', 'form', false).then(res => {
                if (res.code === 0) {
                    this.availableAmount = res.data.distUserInfo.avaibleAmount || 0;
                }
            }).catch(err => {
                console.error('加载用户信息失败:', err);
            });
        },
        
        // 加载提现记录列表
        loadWithdrawList() {
            if (this.loading) return;
            this.loading = true;
            
            const params = {
                pageNum: this.pageNum.toString(),
                pageSize: this.pageSize.toString()
            };
            
            this.$api.req('/station/account/page-withdraw', params, 'post', 'form', false).then(res => {
                uni.stopPullDownRefresh();
                this.loading = false;
                
                if (res.code === 0) {
                    if (this.pageNum === 1) {
                        this.withdrawList = res.data.rows || [];
                    } else {
                        this.withdrawList = [...this.withdrawList, ...(res.data.rows || [])];
                    }
                } else {
                    this.f.msg(res.message || '加载失败');
                }
            }).catch(err => {
                uni.stopPullDownRefresh();
                this.loading = false;
                this.f.msg('网络错误，请重试');
                console.error('加载提现记录失败:', err);
            });
        },
        
        // 加载更多
        loadMore() {
            this.pageNum++;
            this.loadWithdrawList();
        },
        
        // 显示申请弹窗
        showApplyModal() {
            this.showModal = true;
            this.applyAmount = '';
        },
        
        // 隐藏申请弹窗
        hideApplyModal() {
            this.showModal = false;
            this.applyAmount = '';
            this.username = '';
        },
        
        // 验证提现金额
        validateAmount() {
            const amount = parseFloat(this.applyAmount);
            if (isNaN(amount)) {
                this.applyAmount = '';
                return;
            }
            if (amount > this.availableAmount) {
                this.f.msg('提现金额不能超过可提现金额');
                this.applyAmount = this.availableAmount.toString();
            }
        },
        
        // 提交提现申请
        submitApply() {
            const amount = parseFloat(this.applyAmount);
            
            if (!this.username.trim()) {
                this.f.msg('请输入实名姓名');
                return;
            }
            
            if (amount < 1 || amount > 200) {
                this.f.msg('单次提现金额最低为1元，最高200元');
                return;
            }
            
            if (amount > this.availableAmount) {
                this.f.msg('提现金额不能超过可提现金额');
                return;
            }
            
            uni.showModal({
                title: '确认提现',
                content: `确认申请提现 ¥${amount} 吗？\n提现人：${this.username}`,
                success: (res) => {
                    if (res.confirm) {
                        this.doApplyWithdraw(amount);
                    }
                }
            });
        },
        
        // 执行提现申请
        doApplyWithdraw(amount) {
            const params = {
                username: this.username.trim(),
                amount: amount.toString()
            };
            
            this.$api.req('/station/account/apply-withdraw', params, 'post', 'form', false).then(res => {
                if (res.code === 0) {
                    this.f.msg('提现申请提交成功，请等待审批');
                    this.hideApplyModal();
                    this.pageNum = 1;
                    this.loadWithdrawList();
                    this.loadUserInfo(); // 刷新可提现金额
                } else {
                    this.f.msg(res.message || '申请失败');
                }
            }).catch(err => {
                this.f.msg('网络错误，请重试');
                console.error('提现申请失败:', err);
            });
        },
        
        // 确认收款（调用微信商家转账）
        confirmReceive(item) {
            // 检查微信版本是否支持
            if (uni.canIUse('requestMerchantTransfer')) {
                // 这里需要后端提供商家转账的相关参数
                // 实际开发中，需要调用后端接口获取 mchId, package 等参数
                this.requestMerchantTransfer(item);
            } else {
                uni.showModal({
                    content: '您的微信版本过低，请更新至最新版本。',
                    showCancel: false,
                });
            }
        },
        
        // 调用微信商家转账
        requestMerchantTransfer(item) {
            // 先调用后端接口获取转账参数
            this.getTransferParams(item.id).then(params => {
                // 解析 channelNotifyData 字符串为 JSON 对象
                const channelData = JSON.parse(params.channelNotifyData);
                
                uni.requestMerchantTransfer({
                    mchId: params.channelConfig.mchId,
                    appId: params.channelConfig.appId,
                    package: channelData.rawData.packageInfo,
                    success: (res) => {
                        console.log('转账成功:', res);
                        this.f.msg('收款成功');
                        // 刷新列表
                        this.pageNum = 1;
                        this.loadWithdrawList();
                    },
                    fail: (res) => {
                        console.log('转账失败:', res);
                        this.f.msg('收款失败，请重试');
                    },
                });
            }).catch(err => {
                this.f.msg('获取转账参数失败');
                console.error('获取转账参数失败:', err);
            });
        },
        
        // 获取转账参数（需要后端提供接口）
        getTransferParams(withdrawId) {
            return new Promise((resolve, reject) => {
                // 这里调用后端接口获取转账参数
                // 实际接口需要根据后端提供的接口进行调整
                this.$api.req('/pay/transfer/get', { id: withdrawId }, 'get', 'form', false).then(res => {
                    if (res.code === 0) {
                        console.log('获取转账参数成功:', res.data);
                        
                        resolve(res.data);
                    } else {
                        reject(new Error(res.message));
                    }
                }).catch(reject);
            });
        },
        
        // 获取状态文本
        getStatusText(status) {
            const statusMap = {
                '1': '申请中',
                '2': '审核成功',
                '3': '审核拒绝',
                '4': '审核处理中',
                '100': '已收款',
            };
            return statusMap[status] || '未知状态';
        },
        

    }
}
</script>

<style scoped>
.container {
    background-color: #f5f5f5;
    min-height: 100vh;
}

/* 头部信息 */
.header-info {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 40rpx 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.balance-info {
    flex: 1;
}

.balance-label {
    color: rgba(255, 255, 255, 0.8);
    font-size: 28rpx;
    display: block;
    margin-bottom: 10rpx;
}

.balance-amount {
    color: #fff;
    font-size: 48rpx;
    font-weight: bold;
}

.apply-btn {
    background-color: #fff;
    padding: 20rpx 40rpx;
    border-radius: 50rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.apply-text {
    color: #667eea;
    font-size: 28rpx;
    font-weight: bold;
}

/* 记录列表 */
.record-list {
    padding: 30rpx;
}

.list-header {
    margin-bottom: 30rpx;
}

.list-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}

.empty-state {
    text-align: center;
    padding: 100rpx 0;
}

.empty-text {
    color: #999;
    font-size: 28rpx;
}

/* 记录项 */
.record-item {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.record-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
}

.record-num {
    font-size: 28rpx;
    color: #666;
}

.record-status {
    font-size: 24rpx;
    padding: 8rpx 16rpx;
    border-radius: 20rpx;
    font-weight: bold;
}

.status-pending {
    background-color: #fff3cd;
    color: #856404;
}

.status-approved {
    background-color: #d4edda;
    color: #155724;
}

.status-rejected {
    background-color: #f8d7da;
    color: #721c24;
}

.status-completed {
    background-color: #d1ecf1;
    color: #0c5460;
}

.record-content {
    margin-bottom: 20rpx;
}

.amount-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10rpx;
}

.amount-label {
    font-size: 28rpx;
    color: #666;
}

.amount-value {
    font-size: 28rpx;
    color: #333;
    font-weight: bold;
}

.amount-value.highlight {
    color: #f56c6c;
}

.record-footer {
    border-top: 1rpx solid #eee;
    padding-top: 20rpx;
}

.time-text {
    font-size: 24rpx;
    color: #999;
    display: block;
    margin-bottom: 5rpx;
}

.action-btn {
    margin-top: 20rpx;
    text-align: right;
}

.receive-btn {
    background-color: #67c23a;
    color: #fff;
    border: none;
    padding: 16rpx 32rpx;
    border-radius: 8rpx;
    font-size: 26rpx;
}

.received-text {
    color: #28a745;
    font-size: 26rpx;
    font-weight: bold;
    padding: 16rpx 32rpx;
}

/* 弹窗样式 */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.modal-content {
    background-color: #fff;
    border-radius: 16rpx;
    width: 600rpx;
    max-height: 80vh;
    overflow: hidden;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;
}

.modal-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}

.modal-close {
    font-size: 40rpx;
    color: #999;
    line-height: 1;
}

.modal-body {
    padding: 30rpx;
}

.form-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
}

.form-label {
    font-size: 28rpx;
    color: #333;
}

.form-value {
    font-size: 28rpx;
    color: #f56c6c;
    font-weight: bold;
}

.form-input {
    border: 1rpx solid #ddd;
    border-radius: 8rpx;
    padding: 20rpx;
    font-size: 28rpx;
    flex: 1;
    margin-left: 20rpx;
}

.tips {
    background-color: #f8f9fa;
    padding: 20rpx;
    border-radius: 8rpx;
    margin-top: 20rpx;
}

.tips-text {
    font-size: 24rpx;
    color: #666;
    display: block;
    margin-bottom: 8rpx;
}

.modal-footer {
    display: flex;
    border-top: 1rpx solid #eee;
}

.cancel-btn, .confirm-btn {
    flex: 1;
    padding: 30rpx;
    border: none;
    font-size: 28rpx;
}

.cancel-btn {
    background-color: #f8f9fa;
    color: #666;
}

.confirm-btn {
    background-color: #667eea;
    color: #fff;
}

.confirm-btn:disabled {
    background-color: #ccc;
    color: #999;
}
</style>